package socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2019-06-12 08:54:00
 */
public class Server01 {

    public static String test01(String command){
        String res = "";
        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String str = "";
            while ((str = br.readLine()) != null){
                res += str + "\r\n";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(8989);
            Socket s = ss.accept();
            InputStream is = s.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            OutputStream os = s.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            while (true){
                String msg = dis.readUTF();
                System.out.println("收到客户端信息"+msg);

                Map<String, Object> map = JSONObject.parseObject(msg, Map.class);
                Integer op = (Integer) map.get("op");
                String exec = (String) map.get("exec");

                String res = test01(exec);

                Map<String,Object> resMap = new HashMap<>();
                resMap.put("exec", exec);
                resMap.put("data", res);
                dos.writeUTF(JSON.toJSONString(resMap));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
